// store 实例
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 每次进入的时候 从localStage读取购物车商品数据
let goodsData = JSON.parse(localStorage.getItem('cart') || '[]');
const store = new Vuex.Store({
  state: {
    dataList: goodsData // 购物车中商品对象
  },
  mutations: {
    // 购物车商品数据添加
    insertCart: function(state, goods)  {
      // 判断是否已经存在：存在，更新数量；否则，添加
      let flag = state.dataList.some( item => {
        if (item.id === goods.id) {
          item.count += goods.count;
          return true;
        }
      });
      if (!flag) {
        state.dataList.push(goods);
      }

      // 数据同步保存到localStaorage中
      this.commit('updateLocal');
    },
    // 更新购物车中商品信息
    updateCart: function(state, goods) {
      state.dataList.some( item => {
        if (item.id === goods.id) {
          item.count = goods.count;
          return true;
        }
      });
      // 数据同步保存到localStaorage中
      this.commit('updateLocal');

    },
    // 删除商品
    deleteCart: function(state, gid) {
      
      state.dataList.some( (item, index) => {
       if (item.id === gid) {
         
         state.dataList.splice(index, 1);
         return true;
       }
      });
      
      // 数据同步保存到localStaorage中
      this.commit('updateLocal');

    },
    // 把数据同步保存到localStaorage中
    updateLocal: function(state) {
      localStorage.setItem('cart', JSON.stringify(state.dataList));
    },
    // 改变选中状态
    updateSelected(state, gid) {
      state.dataList.some( item => {
        if (item.id === gid) {
         item.selectedFlag = !item.selectedFlag;
         return true;
        }
       });
       
       // 数据同步保存到localStaorage中
       this.commit('updateLocal');
    }
  },
  getters: {
    // 获取购物车中商品总数量
    getTotalCount: state => {
      let total = 0;
      state.dataList.forEach( item => {
        total += item.count;
      });
      return total;
    },
    getIds: state => {
      let ids = [];
      state.dataList.forEach( item => {
        ids.push(item.id);
      });
      return ids;
    },
    getCountById: state => {
      let o = {};
      state.dataList.forEach( item => {
        o[item.id] = item.count;
      });
      return o;
    },
    getSelectedById: state => {
      let o = {};
      state.dataList.forEach( item => {
        o[item.id] = item.selectedFlag;
      });
      return o;
    },
    getTotalCountAndPrice(state) {
      let o = {totalCount: 0, totalPrice: 0};
      state.dataList.forEach( item => {
        if (item.selectedFlag) {
          o.totalCount += item.count;
          o.totalPrice += item.count * item.price;
        }
      });
      return o;
    }
  }
})
export default store;